var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel;


    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            initValue:[user.code],
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    let salesmanList=[];
    let deptSalesmanList=[];
    layer.ready(function () {
        //获取所有公司信息
        $.ajax({
            url: "receivePayment/getCompanyInfo",
            success: function (data) {
                if (data.status == 200) {
                    for (let i in data.data) {
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();
        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", userTree);
        } else {
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}]);
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
        } else {
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }

        let fls=JSON.parse(window.sessionStorage.getItem("fls"));//=getdictionary(6,27);//客户类型
        for (let i in fls){
            $('#customerType').append(new Option(fls[i].name, fls[i].code));
        }

    });
    form.render();//表单刷新



    let initData = [];
    table.render({
        elem: '#offerselect'
        , data: initData
        , toolbar: '#offertoolbar'
        , cols: [[
            //主表
            {field: 'numbers',width: 50,type:'numbers',title:'序号'}
            , {field: 'contractNo', title: '外销合同号', sort: true, width: 200, align: 'center'}
            , {field: 'signingDateStr', title: '第一次签约日期', sort: true, width: 200, align: 'center'}
            , {field: 'code', title: '客户编码', sort: true, width: 200, align: 'center'}
            , {field: 'name', title: '客户名称', sort: true, width: 200, align: 'center'}
            , {field: 'abbreviation', title: '简称', sort: true, width: 200, align: 'center'}
            , {field: 'typeName', title: '客户类型', sort: true, width: 200, align: 'center'}
            , {field:'salesmanName', title:'业务员',sort:true,width: 200, align: 'center'}
            , {field:'address', title:'客户地址',sort:true,width: 200, align: 'center'}
            , {field: 'levelName', title: '等级', sort: true, width: 200, align: 'center'}
            , {field:'accountPeriod', title:'账期',sort:true,width: 200, align: 'center'}
            , {field:'creditLine', title:'信用额度',sort:true,width: 200, align: 'center'}
            , {field:'country', title:'国家',sort:true,width: 200, align: 'center'}
            , {field:'sourceOfCustomers', title:'客户来源',sort:true,width: 200, align: 'center'}
        ]]
        , id: 'maininformationtableid'
        , height: $(document).height() - $('#offerselect').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
    });



    //搜索提交
    form.on('submit(submitform)', function(data){
        if (isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            data.field.salesmanCode=user.code;
        }
        table.reload('maininformationtableid', {
            page: {
                limit:300,
                curr: 1
            },
            url:'exportContract/getFirstCustomerInfoListByPage',
            where:  data.field
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        if (isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            queryReq.field.salesmanCode=user.code;
        }
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"exportContract/getFirstCustomerInfoListExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '客户订单第一次记录.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    document.getElementById('clear').onclick = function(){
        salesmanList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
    };
    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});
